import request from './request'

// 获取对话列表
export const getConversations = () => {
  return request.get('/conversations').then(response => {
    // 后端返回的是 ConversationListResponse 格式，需要提取 conversations 数组
    return response.conversations || response
  })
}

// 流式发送消息
export const sendMessageStream = async (conversationId, content, onMessage, onError, onComplete) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }

    console.log('发送流式消息:', { conversationId, content })

    // 使用 vite proxy 配置的 /api 路径
    const apiUrl = '/api/chat'
    console.log('流式请求 URL:', apiUrl)
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        content,
        conversation_id: conversationId
      })
    })

    console.log('流式响应状态:', response.status, response.statusText)

    if (!response.ok) {
      const errorText = await response.text()
      console.error('流式请求失败:', errorText)
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() // 保留最后一个不完整的行

      for (const line of lines) {
        if (line.trim() === '') continue // 跳过空行
        
        if (line.startsWith('data: ')) {
          try {
            const jsonStr = line.slice(6).trim()
            if (jsonStr === '') continue // 跳过空数据
            
            const data = JSON.parse(jsonStr)
            console.log('收到流式数据:', data)
            
            if (data.type === 'content') {
              onMessage({ type: 'content', content: data.content })
            } else if (data.type === 'reasoning') {
              onMessage({ type: 'reasoning', content: data.content })
            } else if (data.type === 'error') {
              onError(data.content)
              return
            } else if (data.type === 'end') {
              onComplete()
              return
            }
          } catch (e) {
            console.warn('解析SSE数据失败:', e, 'line:', line)
          }
        }
      }
    }
    
    // 如果循环结束但没有收到end信号，手动调用完成回调
    onComplete()
  } catch (error) {
    console.error('流式请求失败:', error)
    onError(error.message || '发送消息失败')
  }
}

// 发送消息（非流式，兼容旧版本）
export const sendMessage = (conversationId, content) => {
  return request.post('/chat/simple', { 
    content,
    conversation_id: conversationId 
  }).then(response => ({
    reply: response.message
  }))
}

// 创建新对话
export const createConversation = (title = '新对话') => {
  return request.post('/conversations', { title })
}

// 删除对话
export const deleteConversation = (id) => {
  return request.delete(`/conversations/${id}`)
}

// 更新对话标题
export const updateConversationTitle = (id, title) => {
  return request.put(`/conversations/${id}`, { title })
}
